package net.chrisrichardson.ec2deployer.cluster

import net.chrisrichardson.ec2deployer.core.AWSProperties
import net.chrisrichardson.ec2deployer.core.EC2
import groovy.mock.interceptor.MockFor

class SimpleClusterTest extends GroovyTestCase {

    AWSProperties awsProperties
    ClusterSpec clusterSpec
    MockFor mockClusterInstance
    MockFor mockEc2

    public void setUp() {
        mockClusterInstance = new MockFor(ClusterInstance)
        mockEc2 = new MockFor(EC2)

        clusterSpec = new ClusterSpec().tomcats(1).slaves(1).webApp('target/ptrack', "ptrack").catalinaOptsBuilder({builder, databasePrivateDnsName ->}).schema("ptrack", ["ptrack": "ptrack"])

        def props = new Properties()
        props["accessKey"] = "foo"
        awsProperties = new AWSProperties(props)

    }

    void testCloneCluster() {
        mockClusterInstance.demand.start {}

        mockClusterInstance.demand.snapshotWebApplications { "s3://mybucket/mywebapps.tar" }
        mockClusterInstance.demand.dbSave {}

        mockClusterInstance.demand.allocateAndAssignHosts {}
        mockClusterInstance.demand.startTiers {}

        mockEc2.demand.startPolling {}
        mockEc2.demand.getAwsProperties {
            awsProperties
        }

        mockEc2.use {
        mockClusterInstance.use {
            def ec2 = new EC2(awsProperties)

            def cluster1 = new SimpleCluster(ec2, clusterSpec)

            cluster1.start() 
            def cluster2 = cluster1.cloneCluster()
            assert cluster2 != null
        }
        }
    }

    void testCloneClusterWithEbs() {
        clusterSpec.withNewEbsVolume(10, "/dev/sdh")
        mockClusterInstance.demand.start {}

        mockClusterInstance.demand.snapshotWebApplications { "s3://mybucket/mywebapps.tar" }
        mockClusterInstance.demand.snapshotDatabase { "snapshot-12233"}

        mockClusterInstance.demand.allocateAndAssignHosts {}
        mockClusterInstance.demand.startTiers {}

        mockEc2.demand.startPolling {}

        mockEc2.use {
        mockClusterInstance.use {
            def ec2 = new EC2(awsProperties)

            def cluster1 = new SimpleCluster(ec2, clusterSpec)

            cluster1.start()
            SimpleCluster cluster2 = cluster1.cloneCluster()

            assertEquals "snapshot-12233", cluster2.spec.ebsVolume.snapshotId
        }
        }
    }

    void testMakeS3PathForClone() {
        def ec2 = new EC2(awsProperties)
        def cluster1 = new SimpleCluster(ec2, clusterSpec)

        assertEquals "foo.tmp-clone-db/snapshot", cluster1.makeS3PathForClone()
    }

}